<template>
    <div class="flow-content">
        <div class="flow-content">
            <!-- 主体部分：左中右 -->
            <div class="flow-container">
                <div class="sidebar">
                    <h3>节点</h3>
                    <div
                        v-for="node in presetNodes"
                        :key="node.type"
                        class="draggable-node"
                        :draggable="true"
                        @dragstart="onDragStart($event, node)"
                    >
                        {{ node.data.label }}
                    </div>
                </div>
                <!-- 画布 -->
                <div class="flow-area" @drop="onDrop" @dragover="onDragOver">
                    <VueFlow
                        v-model:nodes="nodes"
                        v-model:edges="edges"
                        @node-click="onNodeClick"
                        @connect="onConnect"
                        :selectEdgesOnClick="true"
                    >
                        <template #edge-custom="props">
                            <BaseEdge
                                :id="props.id"
                                :path="
                                    getStraightPath({
                                        sourceX: props.sourceX,
                                        sourceY: props.sourceY,
                                        targetX: props.targetX,
                                        targetY: props.targetY
                                    })[0]
                                "
                                :label-x="(props.sourceX + props.targetX) / 2"
                                :label-y="(props.sourceY + props.targetY) / 2"
                                label-bg-style="fill: whitesmoke"
                            />
                        </template>

                        <!--                        自定义节点-->
                        <template #node-start="nodeProps">
                            <div class="custom-node">
                                <div class="handle">
                                    <handle type="source" position="right" />
                                </div>
                                {{ nodeProps.data.label }}
                            </div>
                        </template>
                        <template #node-input="nodeProps">
                            <div class="custom-node" :style="{ backgroundColor: getBacColor(nodeProps) }">
                                <handle type="target" position="left" />
                                {{ nodeProps.data.label }}
                                <handle type="source" position="right" />
                                <div
                                    class="node-delete-btn"
                                    v-if="nodeProps.selected"
                                    @click.stop="removeNode(nodeProps.id)"
                                >
                                    ✖
                                </div>
                                {{ nodeProps.data.sopStep }}
                            </div>
                        </template>
                        <template #node-output="nodeProps">
                            <div class="custom-node">
                                <div class="handle">
                                    <handle type="target" position="left" />
                                </div>
                                <div class="node-content">{{ nodeProps.data.label }}</div>
                                <div
                                    class="node-delete-btn"
                                    v-if="nodeProps.selected"
                                    @click.stop="removeNode(nodeProps.id)"
                                >
                                    ✖
                                </div>
                            </div>
                        </template>
                        <Background />
                        <Controls />
                    </VueFlow>
                </div>
            </div>
        </div>
        <a-button type="primary" @click="onSave">保存流程</a-button>
    </div>
    <div>{{ nodes }}</div>
    ==============================================
    <div>{{ edges }}</div>
</template>

<script setup lang="tsx">
import {
    h,
    ref,
    reactive,
    toRaw,
    markRaw,
    watch,
    computed,
    onBeforeMount,
    onMounted,
    onBeforeUnmount,
    onUnmounted,
    onActivated,
    onDeactivated
} from 'vue'
import { useRoute, useRouter } from 'vue-router'
const router = useRouter()
const route = useRoute()
import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios'
import {
    cloneDeep,
    localGet,
    merge,
    getDifferenceArray,
    traversalTreeStructure,
    checkCaseCondition,
    renderStringInTemplate,
    handleBreadcrumbJump,
    throttle,
    permission,
    getComponentParamsValue
} from '@/utils/index'
import { isNullOrEmpty, isEmptyArr, isNullOrUnDef, isContained, isArray, isEmpty, isObject } from '@/utils/is'
import dayjs from 'dayjs'
import { getPagePcChartsDataSourceConvert } from '@/utils/chart'
import { message, notification, Modal } from 'ant-design-vue'
import {
    propertyFormatByNumber,
    propertyFormatByPercentage,
    propertyFormatByDate,
    parseSubFromDataList
} from '@/utils/format'
import colorTheme from '@/design/custom-theme.json'
//     拖拉拽
// 定制化代码
import { VueFlow, useVueFlow, Handle, Panel } from '@vue-flow/core'
import { Background } from '@vue-flow/background'
import { Controls } from '@vue-flow/controls'
import '@vue-flow/core/dist/style.css'
import '@vue-flow/core/dist/theme-default.css'
import { Position } from '@vue-flow/core'
// 确保从正确路径导入 BaseEdge
import { BaseEdge } from '@vue-flow/core' // 注意：不是 '@vue-flow/additional-components'
import { getStraightPath, getBezierPath, getSmoothStepPath } from '@vue-flow/core'
// import { backgroundColor } from 'html2canvas/dist/types/css/property-descriptors/background-color'
// 🟢 1. 预配置节点列表
const presetNodes = [
    // { id: '1', type: 'start', targetPosition: Position.Bottom, data: { label: '开始' }, isStart: true },
    { id: '2', type: 'input', sourcePosition: Position.Bottom, data: { label: '步骤' } },
    { id: '4', type: 'output', targetPosition: Position.Top, data: { label: '结束' } }
]

// 🟢 2. 画布数据
const nodes = ref([])
const edges = ref([])

// 🟢 3. 节点配置弹窗
const selectedNode = ref({})
const isShowForm = ref(false)

// 节点点击 - 弹窗
const onNodeClick = (event, node) => {
    console.log(event)
    if (event.node.type === 'input') {
        selectedNode.value = event.node.data
        isShowForm.value = true
    } else {
        selectedNode.value = {}
        isShowForm.value = false
    }
}

// 拖拽相关
const onDragStart = (event, node) => {
    event.dataTransfer.setData('application/vueflow', JSON.stringify(node))
    event.dataTransfer.effectAllowed = 'move'
}

const onDragOver = event => {
    event.preventDefault()
    event.dataTransfer.dropEffect = 'move'
}

const onDrop = event => {
    event.preventDefault()
    const nodeData = JSON.parse(event.dataTransfer.getData('application/vueflow'))
    const bounds = event.currentTarget.getBoundingClientRect()
    const position = { x: event.clientX - bounds.left, y: event.clientY - bounds.top }

    const newNode = {
        id: `${nodeData.type}-${Date.now().toString(36)}`,
        type: nodeData.type,
        isStart: nodeData.isStart,
        position,
        data: { label: nodeData.data.label, sopStep: undefined, solverRole: undefined },
        targetPosition: nodeData.targetPosition,
        sourcePosition: nodeData.sourcePosition
    }
    nodes.value.push(newNode)
}

// // 节点删除方法
function removeNode(id) {
    nodes.value = nodes.value.filter(node => node.id !== id)
    // 同时删除相关连线
    edges.value = edges.value.filter(edge => edge.source !== id && edge.target !== id)
}

// 连接线
const { addEdges } = useVueFlow()
const onConnect = params => {
    console.log('params', params) // 确保打印出连线参数
    // 确保每个连线数据都符合 VueFlow 的要求
    const newEdge = {
        ...params,
        // 确保路径、样式等数据正确,
        type: 'custom'
    }
    edges.value = [...edges.value, newEdge] // 手动更新 edges 数据
}

// 删除连线
function removeEdge(id) {
    edges.value = edges.value.filter(edge => edge.id !== id)
}

// 保存
const onSave = () => {
    console.log(nodes.value)
    console.log(edges.value)
}
function getBacColor(props) {
    console.log(props, 'asdasdsdsadasds')
    if (!props.data.sopStep || !props.data.solverRole) {
        return 'red'
    } else {
        return 'blue'
    }
}
watch(
    () => [selectedNode.value.sopStep, selectedNode.value.solverRole],
    () => {
        const index = nodes.value.findIndex(node => node.id === selectedNode.value.id)
        if (index !== -1) {
            nodes.value[index].data.sopStep = selectedNode.value.sopStep
            nodes.value[index].data.solverRole = selectedNode.value.solverRole
        }
    },
    { deep: true }
)
nodes.value = [
    {
        id: 'start-1',
        type: 'start',
        data: { label: '开始' },
        position: { x: 50, y: 100 },
        sourcePosition: Position.Right
    }
]
</script>

<style>
/* 全局容器样式 */
.flow-content {
    display: flex;
    flex-direction: column;
    height: 500px;
    overflow: auto;
    background-color: #f5f7fa;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}

/* 顶部操作栏 */
.flow-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 24px;
    background-color: #fff;
    border-bottom: 1px solid #e8e8e8;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.flow-header-actions {
    display: flex;
    gap: 12px;
}

/* 主体容器 */
.flow-container {
    display: flex;
    flex: 1;
    overflow: hidden;
}

/* 左侧边栏 */
.sidebar {
    width: 220px;
    padding: 16px;
    background-color: #fff;
    border-right: 1px solid #e8e8e8;
    overflow-y: auto;
}

.sidebar h3 {
    margin: 0 0 16px 0;
    padding-bottom: 8px;
    color: #333;
    font-size: 16px;
    font-weight: 500;
    border-bottom: 1px solid #f0f0f0;
}

.draggable-node {
    padding: 10px 12px;
    margin-bottom: 8px;
    background-color: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 6px;
    color: #495057;
    font-size: 14px;
    cursor: grab;
    transition: all 0.2s ease;
}

.draggable-node:hover {
    background-color: #e9ecef;
    border-color: #dee2e6;
}

/* 画布区域 */
.flow-area {
    flex: 1;
    position: relative;
    background-color: #f8f9fa;
    overflow: hidden;
}
/* 节点样式 */
.custom-node {
    position: relative;
    height: 50px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    font-size: 14px;
    color: #fff;
    transition: all 0.2s ease;
    border: 2px solid transparent;
}
/* 不同类型节点颜色 */
.vue-flow__node-start .custom-node {
    background: linear-gradient(135deg, #52c41a, #73d13d);
    width: 50px;
    border-radius: 50%;
}

.vue-flow__node-input .custom-node {
    background: linear-gradient(135deg, #1890ff, #40a9ff);
}

.vue-flow__node-output .custom-node {
    width: 50px;
    border-radius: 50%;
    background: linear-gradient(135deg, #722ed1, #9254de);
}
.vue-flow__node-output {
    padding: 0;
    width: unset;
    border: none;
    border-radius: 50%;
}
.vue-flow__node-output.selected {
    border: none;
}
.vue-flow__node-input {
    padding: 0;
    border: none;
}
.vue-flow__node-input.selected {
    border: none;
}
/* 节点选中状态 */
.vue-flow__node.selected .custom-node {
    border-color: #fff;
    box-shadow: 0 0 0 3px rgba(24, 144, 255, 0.5);
}

/* 节点删除按钮 */
.node-delete-btn {
    position: absolute;
    top: -8px;
    right: -8px;
    width: 20px;
    height: 20px;
    background: #ff4d4f;
    color: white;
    border-radius: 50%;
    text-align: center;
    line-height: 20px;
    font-size: 12px;
    cursor: pointer;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
    opacity: 1;
    transition: opacity 0.2s ease;
}
/* 节点新增下一个按钮 */
.add-next-btn {
    position: absolute;
    top: -15px;
    right: 50px;
    width: 20px;
    height: 20px;
    background: #ff4d4f;
    color: white;
    border-radius: 50%;
    text-align: center;
    line-height: 20px;
    font-size: 12px;
    cursor: pointer;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
    opacity: 1;
    transition: opacity 0.2s ease;
}
.node-add-btn {
    position: absolute;
    top: -8px;
    right: -8px;
    width: 20px;
    height: 20px;
    background: #ff4d4f;
    color: white;
    border-radius: 50%;
    text-align: center;
    line-height: 20px;
    font-size: 12px;
    cursor: pointer;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
    opacity: 1;
    transition: opacity 0.2s ease;
}

.custom-node:hover .node-delete-btn {
    opacity: 1;
}

.node-delete-btn:hover {
    background: #ff7875;
}

/* 连线样式 */
.vue-flow__edge-path {
    stroke: #888;
    stroke-width: 2;
}

.vue-flow__edge.selected .vue-flow__edge-path {
    stroke: #1890ff;
    stroke-width: 3;
}

/* 连线删除按钮 */
.edge-delete-fo {
    pointer-events: all;
}

.edge-delete-btn {
    width: 20px;
    height: 20px;
    background: #ff4d4f;
    color: white;
    border-radius: 50%;
    text-align: center;
    line-height: 20px;
    font-size: 12px;
    cursor: pointer;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
    opacity: 1;
    transition: opacity 0.2s ease;
}

.edge-delete-btn:hover {
    background: #ff7875;
}

/* 控制面板样式 */
.vue-flow__controls {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    border-radius: 6px;
    overflow: hidden;
}

.vue-flow__controls-button {
    background-color: #fff;
    border-bottom: 1px solid #f0f0f0;
    transition: background-color 0.2s ease;
}

.vue-flow__controls-button:hover {
    background-color: #f5f5f5;
}

.vue-flow__controls-button svg {
    fill: #595959;
}

/* 背景网格 */
.vue-flow__background {
    background-color: #f8f9fa;
    background-image: linear-gradient(#e9ecef 1px, transparent 1px),
        linear-gradient(90deg, #e9ecef 1px, transparent 1px);
    background-size: 20px 20px;
}

/* 模态框样式 */
.ant-modal-header {
    border-bottom: 1px solid #f0f0f0;
}

.ant-modal-title {
    color: #333;
    font-weight: 500;
}

.ant-form-item-label > label {
    color: #595959;
}
</style>
